<template>
  <div class="params_container">
    <el-card class="box-card">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>商品分类</el-breadcrumb-item>
      </el-breadcrumb>

      <el-alert title="注意： 只允许设置第三级分类相关的参数！"
                type="warning">
      </el-alert>

      <el-row>
        <span>选中商品分类：</span>
        <el-cascader expand-trigger="hover"
                     v-model="selectGoods"
                     :options="goodslist"
                     :props="goodsProps"
                     @change="handleChange"
                     clearable
                     change-on-select></el-cascader>
      </el-row>
      <el-row class="active">
        <el-tabs v-model="activeName"
                 @tab-click="handleClick">
          <el-tab-pane label="动态参数"
                       name="many">
            <el-button type="primary"
                       size="mini"
                       :disabled="btnBool"
                       @click="showDialog = true">
              添加动态参数
            </el-button>
            <el-table :data="manyData"
                      border
                      stripe>
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag v-for="(item, i) in scope.row.attr_vals"
                          :key="i"
                          closable
                          @close="closeTag(i, scope.row)">
                    {{item}}
                  </el-tag>
                  <el-input class="input-new-tag"
                            v-if="scope.row.inputVisible"
                            v-model="scope.row.iptVal"
                            ref="iptRef"
                            size="small"
                            @keyup.enter.native='iptEnter(scope.row)'
                            @blur='iptEnter(scope.row)'></el-input>
                  <el-button v-else
                             class="button-new-tag"
                             size="small"
                             @click="showIpt(scope.row)">
                    + New Tag
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column type="index">
              </el-table-column>
              <el-table-column prop="attr_name"
                               label="参数名称">
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button size="mini"
                             type="primary"
                             icon="el-icon-edit"
                             @click="editDialog(scope.row.attr_id)">编辑</el-button>
                  <el-button size="mini"
                             type="danger"
                             icon="el-icon-delete"
                             @click="removeItem(scope.row.attr_id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="静态属性"
                       name="only">
            <el-button type="primary"
                       size="mini"
                       :disabled="btnBool"
                       @click="showDialog = true">
              添加静态属性
            </el-button>
            <el-table :data="onlyData"
                      border
                      stripe>
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag v-for="(item, i) in scope.row.attr_vals"
                          :key="i"
                          closable
                          @close="closeTag(i, scope.row)">
                    {{item}}
                  </el-tag>
                  <el-input class="input-new-tag"
                            v-if="scope.row.inputVisible"
                            v-model="scope.row.iptVal"
                            ref="iptRef"
                            size="small"
                            @keyup.enter.native='iptEnter(scope.row)'
                            @blur='iptEnter(scope.row)'></el-input>
                  <el-button v-else
                             class="button-new-tag"
                             size="small"
                             @click="showIpt(scope.row)">
                    + New Tag
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column type="index">
              </el-table-column>
              <el-table-column prop="attr_name"
                               label="参数名称">
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button size="mini"
                             type="primary"
                             icon="el-icon-edit"
                             @click="editDialog(scope.row.attr_id)">编辑</el-button>
                  <el-button size="mini"
                             type="danger"
                             icon="el-icon-delete"
                             @click="removeItem(scope.row.attr_id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>

        </el-tabs>
      </el-row>

      <el-dialog :title="'添加' + titleText"
                 :visible.sync="showDialog"
                 @close="addParams"
                 width="30%">
        <el-form label-width="80px"
                 :model="addForm"
                 :rules="addFormRules"
                 ref="addFormRef">
          <el-form-item :label="titleText"
                        prop="attr_name">
            <el-input v-model="addForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="showDialog = false">取 消</el-button>
          <el-button type="primary"
                     @click="addParamsItem">确 定</el-button>
        </span>
      </el-dialog>

      <el-dialog :title="'修改' + titleText"
                 :visible.sync="showEditDialog"
                 @close="closeEdit"
                 width="30%">
        <el-form label-width="80px"
                 :model="editForm"
                 :rules="editFormRules"
                 ref="editFormRef">
          <el-form-item :label="titleText"
                        prop="attr_name">
            <el-input v-model="editForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="showEditDialog = false">取 消</el-button>
          <el-button type="primary"
                     @click="editParams">确 定</el-button>
        </span>
      </el-dialog>

    </el-card>
  </div>
</template>

<script>
export default {
  data () {
    return {
      goodslist: [],
      goodsProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      selectGoods: [],
      activeName: 'many',
      manyData: [],
      onlyData: [],
      addForm: {
        attr_name: ''
      },
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      showDialog: false,
      showEditDialog: false,
      editForm: {},
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      }
      // inputVisible: false,
      // iptVal: ''
    }
  },
  created () {
    this.getGoodList()
  },
  methods: {
    async getGoodList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类数据失败！')
      }
      this.goodslist = res.data
    },
    handleChange () {
      this.getParamsList()
    },
    handleClick () {
      // console.log(this.activeName)
      this.getParamsList()
    },
    async getParamsList () {
      if (this.selectGoods.length !== 3) {
        this.selectGoods = []
        this.manyData = []
        this.onlyData = []
        return
      }
      // console.log(this.selectGoods)
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: { sel: this.activeName }
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数列表数据失败！')
      }
      this.$message.success('获取参数列表数据成功')
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.iptVal = ''
      })
      // console.log(res.data[0].attr_vals)
      if (this.activeName === 'many') {
        this.manyData = res.data
      } else {
        this.onlyData = res.data
      }
    },
    addParams () {
      this.$refs.addFormRef.resetFields()
    },
    addParamsItem () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) {
          return this.$message.error('添加参数失败')
        }
        this.$message.success('添加参数成功')
        this.showDialog = false
        this.getParamsList()
      })
    },
    async editDialog (attr_id) {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${attr_id}`, {
        params: { attr_sel: this.activeName }
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数信息失败！')
      }
      this.editForm = res.data
      this.showEditDialog = true
      // console.log(this.editForm)
    },
    closeEdit () {
      this.$refs.editFormRef.resetFields()
    },
    editParams () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`, {
          attr_name: this.editForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) {
          return this.$message.error('修改参数失败')
        }
        this.$message.success('修改参数成功')
        this.getParamsList()
        this.showEditDialog = false
      })
    },
    async removeItem (attr_id) {
      const confirmRes = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmRes !== 'confirm') {
        return this.$message.info('取消了删除')
      }
      const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${attr_id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除参数失败')
      }
      this.$message.success('删除参数成功')
      this.getParamsList()
    },
    async iptEnter (row) {
      if (row.iptVal.trim().length === 0) {
        row.iptVal = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.iptVal.trim())
      row.iptVal = ''
      row.inputVisible = false

      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) {
        return this.$message.error('修改参数项失败！')
      }
      this.$message.success('修改参数项成功！')
    },
    showIpt (row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.iptRef.$refs.input.focus()
      })
    },
    closeTag (i, row) {
      row.attr_vals.splice(i, 1)
      this.iptEnter(row)
      this.$message.success('参数删除成功')
    }
  },
  computed: {
    btnBool () {
      if (this.selectGoods.length !== 3) {
        return true
      }
      return false
    },
    cateId () {
      if (this.selectGoods.length === 3) {
        // console.log(this.selectGoods)
        return this.selectGoods[2]
      }
      return null
    },
    titleText () {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>

<style lang="less" scoped>
.params_container {
  width: 85%;
  .el-alert {
    margin: 15px 0;
  }
  .active {
    margin-top: 15px;
  }
  .el-table {
    margin: 15px 0;
  }
  .el-tag {
    margin: 5px;
  }
  .input-new-tag {
    width: 95px;
  }
}
</style>
